#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
from typing import List, Dict
from utils.utils import setup_logging
from config import REPO_OWNER, REPO_NAME, ACCESS_TOKEN, GITEE_API_BASE, REQUEST_TIMEOUT

logger = setup_logging("fetch_files")

def fetch_pr_files(pr_number: int, access_token: str = ACCESS_TOKEN) -> List[Dict]:
    """获取单个PR的文件diff"""
    url = f"{GITEE_API_BASE}/repos/{REPO_OWNER}/{REPO_NAME}/pulls/{pr_number}/files"
    headers = {
        "Authorization": f"token {access_token}",
        "Accept": "application/json"
    }
    try:
        response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT)
        if response.status_code != 200:
            logger.error(f"PR#{pr_number} 文件diff请求失败，状态码: {response.status_code}")
            return None
        return response.json()
    except Exception as e:
        logger.exception(f"PR#{pr_number} 文件diff请求异常: {e}")
        return None

def extract_file_diffs(files: List[Dict]) -> List[Dict]:
    """从文件列表中提取diff信息"""
    diffs = []
    if files:
        for f in files:
            filename = f.get('filename')
            patch = f.get('patch', {}).get('diff') if f.get('patch') else None
            if not patch:
                continue
            
            # 解析diff
            from .diff_parser import parse_diff, reconstruct_hunk_diff
            hunks = parse_diff(patch)
            
            for idx, hunk in enumerate(hunks):
                diffs.append({
                    'file': filename,
                    'change_index': idx,
                    'hunk_header': hunk['hunk_header'],
                    'changes': hunk['changes'],
                    'diff': reconstruct_hunk_diff(hunk)
                })
    
    return diffs 